package com.wlyuan.index.remote.consumer;

import com.wlyuan.index.api.ICombineIndexService;
import com.wlyuan.index.remote.message.CombineMessage;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author yuanjie
 */
@Slf4j
@Component
public class CombineMessageConsumer extends AbstractMessageConsumer<CombineMessage> {
    @Resource
    private ICombineIndexService combineIndexService;

    @RabbitListener(bindings = {@QueueBinding(value = @Queue(
            value = Queues.COMBINE_REINDEX),
            exchange = @Exchange(value = Exchanges.TRANSPORT),
            key = {"CombineRefused", "CombineDispatched", "CombineClosed"})
    }, concurrency = "4")
    public void consumeSome(String string) {
        logger.debug("~收到合单消息: {}", string);
        try {
            this.handle(string, CombineMessage.class, message -> {
                var combine = message.getCombine();
                combineIndexService.reindex(combine.getCombineId());
            });
        } catch (Exception e) {
            logger.error("~处理合单消息失败：{}", string, e);
        }
    }

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = Queues.COMBINE),
            exchange = @Exchange(value = Exchanges.TRANSPORT),
            key = {
                    "CombineCreated", "CombineUpdated",
                    "CombineAccepted", "CombinePriceConfirmed",
                    "CombineCloseApplied", "CombineCanceled",
                    "CombineCloseRefused", "CombineBillDayClosed",
                    "CombineBillDayCloseCanceled"
            })}, concurrency = "4")
    public void consume(String string) {
        if (logger.isDebugEnabled()) {
            logger.debug("收到合单消息: {}", string);
        }
        try {
            this.handle(string, CombineMessage.class, message -> {
                var combine = message.getCombine();
                combineIndexService.index(combine);
            });
        } catch (Exception e) {
            logger.error("处理合单消息失败：{}", string, e);
        }
    }
}
